/**
 * 
 */
package com.hz.winnie.demands.service;

import static com.hz.winnie.demands.pojo.DemLifeCycle.OP_TYPE_MODIFY;
import static com.hz.winnie.demands.pojo.DemLifeCycle.OP_TYPE_NEW;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import com.hz.winnie.demands.common.DemandsConstants;
import com.hz.winnie.demands.dao.DemandsDao;
import com.hz.winnie.demands.pojo.DemLifeCycle;
import com.hz.winnie.demands.pojo.Demand;

/**
 * @description 需求服务实现类
 * @author winnie
 * @date 2011-4-6
 * @version 1.0
 */
public class DemandsServiceImpl implements DemandsService {

    private static final Logger logger = LoggerFactory
	    .getLogger(DemandsServiceImpl.class);

    private DemandsDao demandsDao;
    private DemLifeCycleService demLifeCycleService;
    private TransactionTemplate transactionTemplate;

    @Override
    @SuppressWarnings("unchecked")
    public int addDemand(final Demand demand) {
	return (Integer) transactionTemplate.execute(new TransactionCallback() {
	    public Object doInTransaction(TransactionStatus ts) {
		try {
		    /** 1.做新增需求操作 */
		    Integer id = demandsDao.create(demand);
		    /** 2.记录生命周期 */
		    demLifeCycleService.addLifeCycle(assembleLifeCycle(demand,
			    OP_TYPE_NEW));
		    return id;
		} catch (Exception e) {
		    ts.setRollbackOnly();
		    logger.error("addDemand error,demand=" + demand.toString(),
			    e);
		    return null;
		}

	    }
	});
    }

    @Override
    public List<Demand> listDemandsByCondition(Demand demand) {
	List<Demand> demands = demandsDao.listDemandsByCondition(demand);
	return demands;
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * com.hz.winnie.demands.service.DemandsService#updateDemands(com.hz.winnie
     * .demands.pojo.Demand)
     */
    @SuppressWarnings("unchecked")
    @Override
    public boolean updateDemand(final Demand demand) {

	return (Boolean) transactionTemplate.execute(new TransactionCallback() {
	    public Object doInTransaction(TransactionStatus ts) {
		try {
		    Demand oldDemand = demandsDao.getDemandById(String
			    .valueOf(demand.getId()));
		    demand.setOriginalStatus(oldDemand.getStatus());

		    /** 1.做更新需求操作 */
		    demandsDao.update(demand);
		    /** 2.记录生命周期 */
		    demLifeCycleService.addLifeCycle(assembleLifeCycle(demand,
			    OP_TYPE_MODIFY));
		    return Boolean.TRUE;
		} catch (Exception e) {
		    ts.setRollbackOnly();
		    logger.error("updateDemand error,demand="
			    + demand.toString(), e);
		    return Boolean.FALSE;
		}

	    }
	});
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.hz.winnie.demands.service.DemandsService#countIndexMsg(int)
     */
    @Override
    public String countIndexMsg(int userId) {
	Demand demand = new Demand();
	demand.setUserId(userId);
	demand.setIsNew(DemandsConstants.DEM_IS_NEW_YES);
	int count1 = countDemandsByCondition(demand);

	String[] statuslist = { DemandsConstants.DEM_STATUS_UN_FOLLOW,
		DemandsConstants.DEM_STATUS_FOLLOWING };
	demand = new Demand();
	demand.setStatuslist(statuslist);
	demand.setUserId(userId);
	demand.setStartTime(new Date());
	demand.setEndTime(DateUtils.addDays(new Date(), -7));
	int count2 = countDemandsByCondition(demand);

	demand = new Demand();
	demand.setUserId(userId);
	demand.setStatuslist(statuslist);
	demand.setEndTime(new Date());
	int count3 = countDemandsByCondition(demand);

	int all = count1 + count2 + count3;
	StringBuffer result = new StringBuffer();
	result.append(all);
	result.append(",");
	result.append(count1);
	result.append(",");
	result.append(count2);
	result.append(",");
	result.append(count3);
	return result.toString();
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * com.hz.winnie.demands.service.DemandsService#countDemandsByCondition(
     * com.hz.winnie.demands.pojo.Demand)
     */
    @Override
    public int countDemandsByCondition(Demand demand) {
	int count = demandsDao.countDemandsByCondition(demand);
	return count;
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.hz.winnie.demands.service.DemandsService#getDemandById(int)
     */
    @Override
    public Demand getDemandById(String demandId) {
	Demand demand = demandsDao.getDemandById(demandId);
	return demand;
    }/*
      * (non-Javadoc)
      * 
      * @see
      * com.hz.winnie.demands.service.DemandsService#delete(java.lang.String)
      */

    @Override
    public void delete(String demandId) {
	demandsDao.delete(demandId);
    }

    /**
     * 组装生命周期
     * 
     * @param demand
     * @return
     */
    private DemLifeCycle assembleLifeCycle(Demand demand, String opType) {
	DemLifeCycle demLifeCycle = new DemLifeCycle();
	demLifeCycle.setDemId(demand.getId());
	demLifeCycle.setModifier(demand.getUserId());
	demLifeCycle.setOpType(opType);
	demLifeCycle.setToStatus(demand.getStatus());
	demLifeCycle.setOriginalStatus(demand.getOriginalStatus());
	demLifeCycle.setRemark(demand.getRemark());
	return demLifeCycle;
    }

    @Override
    public boolean isSameName(String title, String demandId) {
	List<Demand> list = demandsDao.getDemandsByTitle(title, demandId);
	if (list == null || list.isEmpty()) {
	    return false;
	}
	return true;
    }

    public DemandsDao getDemandsDao() {
	return demandsDao;
    }

    public void setDemandsDao(DemandsDao demandsDao) {
	this.demandsDao = demandsDao;
    }

    public DemLifeCycleService getDemLifeCycleService() {
	return demLifeCycleService;
    }

    public void setDemLifeCycleService(DemLifeCycleService demLifeCycleService) {
	this.demLifeCycleService = demLifeCycleService;
    }

    public TransactionTemplate getTransactionTemplate() {
	return transactionTemplate;
    }

    public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
	this.transactionTemplate = transactionTemplate;
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * com.hz.winnie.demands.service.DemandsService#markReaded(java.lang.String,
     * java.lang.String)
     */
    @Override
    public void markReaded(String demandId, String userId) {
	demandsDao.updateReaded(demandId, userId);
    }

}
